package com.test.hand.server.handler;

import com.test.hand.message.LoginRequestMessage;
import com.test.hand.message.LoginResponseMessage;
import com.test.hand.server.service.UserServiceFactory;
import com.test.hand.server.session.SessionFactory;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
/**
 * description 处理登录请求消息的handler
 * @author zken
 * @CreateDate 2024/11/22 16:39:14
 */
@ChannelHandler.Sharable // 多线程支持
public class LoginRequestMessageHandler extends SimpleChannelInboundHandler<LoginRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginRequestMessage msg) throws Exception {
        String username = msg.getUsername();
        String password = msg.getPassword();
        boolean login = UserServiceFactory.getUserService().login(username, password);
        LoginResponseMessage message;
        if (login) {
            // 绑定channel和用户名称
            SessionFactory.getSession().bind(ctx.channel(), username);
            message = new LoginResponseMessage(true, "登录成功");
        } else {
            message = new LoginResponseMessage(false, "密码或者用户名称错误");
        }
        ctx.writeAndFlush(message);
    }
}
